package com.distribution.system.utils.http;

import com.alibaba.fastjson2.JSONObject;
import lombok.SneakyThrows;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Map;

/**
 * @author huoliping
 * @description 请求工具类
 * @date 2021-01-21 16:57
 **/
public class RequestUtils {
    /**
     * 得到请求参数 中属性值
     *
     * @param request request
     * @param name    属性名
     * @return 属性值
     * @throws IOException 数据流异常
     */
    public static String getRequestValueToGet(HttpServletRequest request, String name) throws IOException {
        String value;
        String method = request.getMethod();
        if (RequestMethod.GET.name().equals(method)) {
            value = request.getParameter(name);
        } else {
            StringBuilder s = new StringBuilder();
            String line;
            while ((line = request.getReader().readLine()) != null) {
                s.append(line);
            }
            Map<?, ?> parse = (Map<?, ?>) JSONObject.parse(s.toString());
            value = (String) parse.get(name);
        }
        return decode(value);
    }


    @SneakyThrows
    public static String getRequestValueToPostJson(HttpServletRequest request, String name) {
        ServletInputStream inputStream = request.getInputStream();
        StringBuilder sb = new StringBuilder();
        String line;

        BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }

        Map<?, ?> parse = (Map<?, ?>) JSONObject.parse(sb.toString());
        return (String) parse.get(name);
    }


    /**
     * 属性值解密
     *
     * @param encodeValue 需要解密的属性值
     * @return 解密的属性值
     * @throws UnsupportedEncodingException 解密异常
     */
    static String decode(String encodeValue) throws UnsupportedEncodingException {
        return URLDecoder.decode(encodeValue, "UTF-8");
    }
}
